/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { CoreTaskImpl } from '../../external/task/core-task-impl.js';
import { IncrementalTask } from '../../external/task/incremental-task.js';
import { HvigorLogger } from '../../log/hvigor-log.js';
import { TaskProxy } from '../task/proxy/task-proxy.js';
import { taskProxyManager } from '../task/proxy/task-proxy-manager.js';
import { coreParameter } from '../data/global-core-parameters.js';

const log = HvigorLogger.getLogger('hvigor-incremental-task');

/**
 * 声明为Incremental,并实现了相关增量方法的task的执行流程
 *
 * @param {CoreTaskImpl} coreTask
 */
export async function doIncrementalTask(coreTask: CoreTaskImpl) {
  const incrementalTask: IncrementalTask = coreTask as IncrementalTask;
  const taskProxy = taskProxyManager.set(incrementalTask.getPath(), new TaskProxy(incrementalTask));

  if (doNotTrackTaskState()) {
    incrementalTask.declareInputs();
    incrementalTask.declareInputFiles();
    await taskProxy.execute();
  } else {
    const isUpToDate = taskProxy.preExecute();

    if (isUpToDate) {
      incrementalTask.taskExecutedStatus.setIsUpToDate(true);
    } else {
      await taskProxy.execute();
    }
  }

  /**
   * 判断该增量任务是否真的执行增量检查和状态跟踪
   * 1. 用户显式关闭hvigor的增量执行能力
   * 2. 用户设置单个任务不需要跟踪执行状态
   *
   * @return {boolean} true/false
   */
  function doNotTrackTaskState(): boolean {
    // hvigor关闭整个增量执行
    if (!coreParameter.startParams.incrementalExecution) {
      return true;
    }

    // 当前任务设置不需要跟踪执行状态
    const unTrackStateReason = coreTask.taskExecutedStatus.unTrackStateReason;

    // 有不需要跟踪执行的原因
    if (unTrackStateReason) {
      log.debug(`${coreTask.getPath()} will not track state,eg do incremental,because:${unTrackStateReason}`);
      return true;
    }
    return false;
  }
}
